package yu.code.consumer.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import yu.code.model.User;
import yu.code.service.UserService;
import yu.code.yurpc.model.RpcRequest;
import yu.code.yurpc.model.RpcResponse;
import yu.code.yurpc.serializer.JdkSerializer;

import java.io.IOException;

/**
 * 静态代理
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        //指定序列化器
        JdkSerializer jdkSerializer = new JdkSerializer();
        //发请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .parameters(new Object[]{user})
                .build();
        try {
            byte[] bytes = jdkSerializer.serialize(rpcRequest);
            byte[] result;
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080").body(bytes).execute()
            ) {
                result = httpResponse.bodyBytes();
            }
            RpcResponse response = jdkSerializer.deserialize(result, RpcResponse.class);
            return (User) response.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
